package org.homonoia.worker.net;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import org.apache.log4j.Logger;
import org.homonoia.worker.core.WorkerNodeService;

public class SocketConnectionListener implements Runnable {

    private static final Logger log = Logger.getLogger(SocketConnectionListener.class);

    private WorkerNodeService workerNodeService = null;
    volatile private boolean stopped = true;

    private ServerSocket sock;

    public SocketConnectionListener(WorkerNodeService workerNodeService)
	    throws NumberFormatException, IOException {
	this.workerNodeService = workerNodeService;

	this.sock = new ServerSocket(Integer.parseInt(workerNodeService.getConfiguration()
		.getProperty("Port")));
    }

    public void run() {

	synchronized (this) {
	    stopped = false;
	}

	Socket incomingSocket = null;

	try {
	    while (!stopped) {
		incomingSocket = sock.accept();
		Thread t = new Thread(new SocketConnection(incomingSocket, workerNodeService));
		t.start();
	    }
	} catch (IOException e) {
	    log.error(e.getMessage(),e);
	}
    }

    public void stop() throws IOException {
	synchronized (this) {
	    stopped = true;
	}

	if (sock != null) {
	    sock.close();
	}
    }

    public boolean isStopped() {
	return stopped;
    }
}
